<template>
  <aside class="sidebar" :class="{ collapsed }">
    <!-- Logo 区域 -->
    <div class="sidebar-header">
      <div class="logo-container">
        <div class="logo-circle">
          <img src="@/assets/十一建logo/logo1.png" alt="十一建logo" class="logo" />
        </div>
        <div v-if="!collapsed" class="logo-info">
          <span class="logo-text"><i>十一</i> · <i>智库</i></span>
        </div>
      </div>
      <!-- 收起/展开按钮移到这里 -->
      <button class="collapse-btn-header" @click="toggleCollapsed">
        <el-icon v-if="!collapsed"><Fold /></el-icon>
        <el-icon v-else><Expand /></el-icon>
      </button>
    </div>
    <!-- 菜单项 -->
    <nav class="sidebar-menu">
      <div 
        v-for="item in items" 
        :key="item.key"
        class="menu-item-group"
      >
        <!-- 主菜单项 -->
        <div 
          class="menu-item"
          :class="{ 
            active: modelValue === item.key || isChildActive(item),
            'has-children': item.children && item.children.length > 0
          }"
          @click="handleItemClick(item)"
        >
          <div class="menu-icon" v-html="item.icon"></div>
          <span v-if="!collapsed" class="menu-label">{{ item.label }}</span>
          <span v-else class="menu-label-collapsed" :title="item.label"></span>
          <div 
            v-if="item.children && item.children.length > 0" 
            class="expand-icon"
            :class="{ expanded: expandedItems.includes(item.key) }"
          >
            <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
              <path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
            </svg>
          </div>
        </div>
        <!-- 子菜单 -->
        <div 
          v-if="item.children && expandedItems.includes(item.key) && !collapsed" 
          class="submenu-list"
        >
          <div 
            v-for="child in item.children" 
            :key="child.key"
            class="submenu-item"
            :class="{ active: modelValue === child.key }"
            @click="handleChildClick(child)"
          >
            <div class="submenu-icon" v-html="child.icon"></div>
            <span class="submenu-label">{{ child.label }}</span>
          </div>
        </div>
      </div>
    </nav>
    <!-- 用户信息 -->
    <div class="sidebar-footer" v-if="!collapsed">
      <div class="user-profile">
        <div class="user-avatar">{{ getAvatarText() }}</div>
        <div class="user-info">
          <span class="user-name">{{ getDisplayName() }}</span>
          <!-- FIXME 临时方案待优化 -->
          <span class="user-role" @click="handleRoleClick">{{ getRoleText() }}</span>
        </div>
      </div>
      <button class="logout-button" @click="$emit('logout')" title="退出登录">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
          <path d="M17 7l-1.41 1.41L18.17 11H8v2h10.17l-2.58 2.59L17 17l5-5zM4 5h8V3H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8v-2H4V5z"/>
        </svg>
      </button>
    </div>

    <!-- 收起状态下的用户信息 -->
    <div class="sidebar-footer-collapsed" v-else>
      <div class="user-avatar-collapsed" :title="getDisplayName()">
        {{ getAvatarText() }}
      </div>
      <button class="logout-button-collapsed" @click="$emit('logout')" title="退出登录">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
          <path d="M17 7l-1.41 1.41L18.17 11H8v2h10.17l-2.58 2.59L17 17l5-5zM4 5h8V3H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8v-2H4V5z"/>
        </svg>
      </button>
    </div>
  </aside>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElIcon } from 'element-plus'
import { Fold, Expand } from '@element-plus/icons-vue'
import { getUserMenus } from '../../api/menu'
import { processMenuData } from '@/utils/menuUtils'

interface SidebarItem {
  key: string
  label: string
  icon: string
  path?: string
  children?: SidebarItem[]
}

interface Props {
  items: SidebarItem[]
  modelValue: string
  username?: string
  userRole?: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:modelValue': [value: string]
  'logout': []
  'collapsed-change': [collapsed: boolean]
}>()

const router = useRouter()
const expandedItems = ref<string[]>(['knowledge-plus', 'recent-chats-parent'])
const collapsed = ref(false)

function toggleCollapsed() {
  collapsed.value = !collapsed.value
  emit('collapsed-change', collapsed.value)
}

function handleItemClick(item: SidebarItem) {
  console.log('点击一级菜单:', item)
  
  if (item.children && item.children.length > 0) {
    // 有子菜单的情况，切换展开状态
    const index = expandedItems.value.indexOf(item.key)
    if (index > -1) {
      expandedItems.value.splice(index, 1)
    } else {
      expandedItems.value.push(item.key)
    }
    
    // 选中当前菜单项
    emit('update:modelValue', item.key)
    
    // 如果有路径，跳转到对应页面
    if (item.path) {
      console.log('跳转到一级菜单路径:', item.path)
      router.push(item.path)
    }
  } else {
    // 没有子菜单，直接跳转
    emit('update:modelValue', item.key)
    
    if (item.path) {
      console.log('跳转到:', item.path)
      router.push(item.path)
    }
  }
}

function handleChildClick(child: SidebarItem) {
  console.log('点击子菜单:', child)
  console.log('当前路由:', router.currentRoute.value.path)
  console.log('所有路由:', router.getRoutes().map(r => ({ name: r.name, path: r.path })))
  
  emit('update:modelValue', child.key)
  if (child.path) {
    console.log('准备跳转到:', child.path)
    router.push(child.path).then(() => {
      console.log('跳转成功')
    }).catch(err => {
      console.error('跳转失败:', err)
    })
  }
}

function isChildActive(item: SidebarItem): boolean {
  if (!item.children) return false
  return item.children.some(child => child.key === props.modelValue)
}

// 获取头像文字
function getAvatarText(): string {
  // 优先使用传入的用户名
  if (props.username) {
    return props.username.charAt(0).toUpperCase()
  }

  // 从localStorage获取当前登录用户名
  const currentUsername = localStorage.getItem('currentUsername')
  if (currentUsername) {
    return currentUsername.charAt(0).toUpperCase()
  }

  // 如果都没有，根据角色返回默认字符
  const userRole = localStorage.getItem('userRole') || 'user'
  switch (userRole) {
    case 'admin':
      return '管'
    case 'staff':
      return '员'
    default:
      return '用'
  }
}

// 获取显示名称
function getDisplayName(): string {
  // 优先使用传入的用户名
  if (props.username) {
    return props.username
  }

  // 从localStorage获取当前登录用户名
  const currentUsername = localStorage.getItem('currentUsername')
  if (currentUsername) {
    return currentUsername
  }

  // 如果都没有，根据角色返回默认名称
  const userRole = localStorage.getItem('userRole') || 'user'
  switch (userRole) {
    case 'admin':
      return '系统管理员'
    case 'staff':
      return '工作人员'
    default:
      return '用户'
  }
}

// 获取角色文字
function getRoleText(): string {
  const userRole = localStorage.getItem('userRole') || 'user'
  switch (userRole) {
    case 'admin':
      return '管理员'
    case 'staff':
      return '工作人员'
    default:
      return '普通用户'
  }
}

// 多角色用户切换角色
function handleRoleClick() {
  // 从 localStorage 获取角色列表
  const userRolesStr = localStorage.getItem('user_roles')
  const userRoles = userRolesStr ? JSON.parse(userRolesStr) : []
  
  // 从 localStorage 获取当前角色
  const currentRole = localStorage.getItem('userRole') || 'user'
  
  // 获取当前角色在角色列表中的下标
  const currentIndex = userRoles.indexOf(currentRole)
  
  if (userRoles.length > 0) {
    // 计算下一个角色的下标
    const nextIndex = (currentIndex + 1) % userRoles.length
    // 将下一个角色值写入 localStorage
    localStorage.setItem('userRole', userRoles[nextIndex])
  }

  // 异步操作，刷新页面需在请求完成后处理
  getUserMenus().then(res => {
    // 获取用户菜单权限
    localStorage.setItem('userMenus', JSON.stringify(processMenuData(res)))
    // 刷新页面
    window.location.reload()
  })
}

// 监听modelValue变化，自动展开对应的父菜单
watch(() => props.modelValue, (newValue) => {
  // 如果选中的是智库+，自动展开
  if (newValue === 'knowledge-plus') {
    if (!expandedItems.value.includes('knowledge-plus')) {
      expandedItems.value.push('knowledge-plus')
    }
  }
  
  // 如果选中的是子菜单项，确保父菜单展开
  props.items.forEach(item => {
    if (item.children) {
      const hasActiveChild = item.children.some(child => child.key === newValue)
      if (hasActiveChild && !expandedItems.value.includes(item.key)) {
        expandedItems.value.push(item.key)
      }
    }
  })
}, { immediate: true })
</script>

<style scoped>
.sidebar {
  width: 260px;
  background: #ffffff;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 40px);
  position: fixed;
  left: 20px;
  top: 20px;
  bottom: 20px;
  z-index: 100;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.08);
  transition: width 0.2s cubic-bezier(.4,0,.2,1);
}
.sidebar.collapsed {
  width: 60px;
}
.collapse-btn-header {
  background: transparent;
  border: none;
  color: #9ca3af;
  cursor: pointer;
  transition: all 0.2s ease;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
}

.collapse-btn-header:hover {
  background: #f3f4f6;
  color: #6b7280;
}

/* 移除原来的悬浮按钮样式 */
.collapse-btn-float {
  display: none;
}
.sidebar-header {
  padding: 20px 16px 16px;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(135deg, #f8faff  0%, #e0e7ff 100%);
  border-radius: 12px 12px 0 0;
}
.sidebar-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 20px;
  right: 20px;
  height: 1px;
  background: linear-gradient(90deg, transparent 0%, rgba(91, 124, 255, 0.3) 50%, transparent 100%);
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 14px;
  width: 100%;
  position: relative;
}

.logo-circle {
  width: 50px;
  height: 50px;
  border-radius: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  position: relative;
  overflow: hidden;
}

.logo-circle::before {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(135deg, rgba(91, 124, 255, 0.05) 0%, rgba(166, 133, 255, 0.05) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
  border-radius: 14px;
}

.logo-circle:hover::before {
  opacity: 1;
}

.logo-circle:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 20px rgba(91, 124, 255, 0.15);
  border-color: rgba(91, 124, 255, 0.2);
}

.logo {
  width: 52px;
  height: 52px;
  object-fit: contain;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;
}

.logo-circle:hover .logo {
  transform: scale(1.08);
}

.logo-info {
  display: flex;
  flex-direction: column;
  flex: 1;
  position: relative;
}

.logo-text {
  font-size: 19px;
  font-weight: 700;
  background: var(--minimal-primary-gradient);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  letter-spacing: 0.8px;
  line-height: 1.3;
  position: relative;
  transition: all 0.3s ease;
}

.logo-text i {
  font-style: italic !important;
  font-weight: 900 !important;
  transform: skew(-8deg) !important;
  display: inline-block !important;
  background: #a685ff !important;
  -webkit-background-clip: text !important;
  -webkit-text-fill-color: transparent !important;
  background-clip: text !important;
  text-shadow: 0 0 1px rgba(91, 124, 255, 0.5) !important;
  -webkit-text-stroke: 0.5px rgba(91, 124, 255, 0.3) !important;
}

.logo-text::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 0;
  height: 2px;
  background: var(--minimal-primary-gradient);
  transition: width 0.3s ease;
  border-radius: 1px;
}

.logo-container:hover .logo-text::after {
  width: 100%;
}

.sidebar-menu {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.menu-item-group {
  margin-bottom: 12px;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  cursor: pointer;
  color: #666;
  font-size: 15px;
  transition: all 0.2s;
  margin: 4px 0;
  border-radius: 10px;
  background: transparent;
  position: relative;
}

.menu-item.has-children {
  padding-right: 40px;
}

.menu-item:hover {
  background: #f8f9fa;
  color: #333;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.menu-item.active {
  background: var(--minimal-primary-gradient);
  color: white;
  box-shadow: 0 4px 12px rgba(91, 124, 255, 0.3);
}

.menu-item.active .menu-icon {
  color: white !important;
}

.menu-item.active .menu-icon svg {
  color: white !important;
  fill: white !important;
}

.menu-item.active .menu-icon svg path {
  fill: white !important;
  color: white !important;
}

.menu-item.active .menu-icon svg * {
  fill: white !important;
  color: white !important;
}

/* 当子菜单被选中时，父菜单的样式 - 与普通选中状态一样 */
.menu-item.has-children.active:not(:hover) {
  background: var(--minimal-primary-gradient);
  color: white;
  box-shadow: 0 4px 12px rgba(91, 124, 255, 0.3);
}

.menu-item.has-children.active:not(:hover) .menu-icon {
  color: white !important;
}

.menu-item.has-children.active:not(:hover) .menu-icon svg {
  color: white !important;
  fill: white !important;
}

.menu-item.has-children.active:not(:hover) .menu-icon svg path {
  fill: white !important;
  color: white !important;
}

.menu-item.has-children.active:not(:hover) .menu-icon svg * {
  fill: white !important;
  color: white !important;
}

.menu-icon {
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.menu-label {
  font-weight: 400;
  font-size: 15px;
}

.menu-label-collapsed {
  display: none;
}

.expand-icon {
  position: absolute;
  right: 12px;
  transition: transform 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
}

.expand-icon.expanded {
  transform: rotate(90deg);
}

.expand-icon svg {
  width: 16px;
  height: 16px;
}

.submenu-list {
  padding-left: 16px;
  margin-top: 8px;
}

.submenu-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 16px;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  transition: all 0.2s;
  margin: 3px 0;
  border-radius: 8px;
  background: transparent;
}

.submenu-item:hover {
  background: #f8f9fa;
  color: #333;
  box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}

.submenu-item.active {
  background: transparent;
  color: #a685ff;
  box-shadow: none;
  font-weight: 600;
  border-left: 3px solid #a685ff;
  padding-left: 13px;
}

.submenu-item.active .submenu-icon {
  color: #a685ff !important;
}

.submenu-item.active .submenu-icon svg {
  color: #a685ff !important;
  fill: #a685ff !important;
}

.submenu-item.active .submenu-icon svg path {
  fill: #a685ff !important;
  color: #a685ff !important;
}

.submenu-item.active .submenu-icon svg * {
  fill: #a685ff !important;
  color: #a685ff !important;
}

.submenu-icon {
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.sidebar-footer {
  padding: 12px 16px;
  border-top: 1px solid #e5e7eb;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-top: auto;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  min-width: 0;
}

.user-avatar {
  width: 36px;
  height: 36px;
  background: var(--minimal-primary-gradient);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  flex-shrink: 0;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
  flex: 1;
}

.user-name {
  font-size: 13px;
  color: #374151;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-role {
  font-size: 11px;
  color: #6b7280;
  font-weight: 400;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

.logout-button {
  padding: 6px 8px;
  background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 11px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.2s;
  flex-shrink: 0;
  min-width: 0;
}

.logout-button:hover {
  background: linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(139, 92, 246, 0.4);
}

/* 收起状态下的用户信息 */
.sidebar-footer-collapsed {
  padding: 12px 16px;
  border-top: 1px solid #e5e7eb;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  margin-top: auto;
}

.user-avatar-collapsed {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: var(--minimal-primary-gradient);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 12px;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  cursor: pointer;
}

.logout-button-collapsed {
  padding: 6px;
  background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  width: 32px;
  height: 32px;
}

.logout-button-collapsed:hover {
  background: linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(139, 92, 246, 0.4);
}
</style> 
